
$(document).ready(function () {
    InitButton2();
    InitExcelHelp();
});
var form1;
//绘制表单
function InitForm1() {
    //清空
    $('#itemForm1').html('');
    form1 = new bsEx.ItemForm('#itemForm1');
    form1.items = $.CookieData.formitem||[
        { type: 'select', name: 'tablename_column_1_A', title: '表名_列名:', select: { data: $.tablename_column, tree: false } },
        { type: 'text', name: 'ope_1', title: '运算符:', value:"=" },
        { type: 'select', name: 'tablename_column_1_B', title: '表名_列名:', select: { data: $.tablename_column, tree: false } },
        { type: 'text', name: 'delbtn', title: '', select: { data: [], tree: false } },
    ];//项
    
    form1.colunb = 4;//列数
    var ope_ = form1.items.filter(function(m){return m.name.indexOf('ope_')>=0});
    var opes = ope_.map(function(t){return t.name});
    form1.readonly = opes;
    form1.requireds = ["tablename_column1","tablename_column2"];
    form1.on('inited',function(){
        $('#delbtn').remove();
        if($.CookieData.rownub && $.rownub == 1){
             $.rownub = $.CookieData.rownub;
        }
        for(var i=2;i<=$.rownub;i++){
            //<button id="btn1" bsexid="bsex1" type="button" class="btn btn-default">默认按钮</button>
            //$('#delbtn_'+i).remove();
            $('#delbtn_'+i).after('<button id="btn_del_'+i+'" index="'+i+'" type="button" class="btn btn-default btnDel">删除</button>');
            $('#delbtn_'+i).remove();
        }
        $('.btnDel').on('click',function(){
            var index = $(this).attr('index');
            var tc_A = form1.items.find(function(m){return m.name == 'tablename_column_'+index+'_A'});
            form1.items.remove(tc_A);
            var ope = form1.items.find(function(m){return m.name == 'ope_'+index});
            form1.items.remove(ope);
            var tc_B = form1.items.find(function(m){return m.name == 'tablename_column_'+index+'_B'});
            form1.items.remove(tc_B);
            var btn = form1.items.find(function(m){return m.name == 'delbtn_'+index});
            form1.items.remove(btn);
            $.FormData = form1.getFormData();
            form1.init();
        })
        form1.setFormData($.FormData)
    })
    //form1.showlabel = false;
    form1.init();//开始显示
    if($.CookieData.formdata){
        setTimeout(function(){
            form1.setFormData($.CookieData.formdata)
        },200)
    }
}
//绘制需要导出的列
function InitButs(){
    $('#btns').html('');
    $('#btns').append('<p/><div id="btngroupid"  data-toggle="buttons" class="btn-group"></div>&nbsp;&nbsp;');
    var btns = [];
    btns.push({id:"btnall",text:'全选'});
    $.tablename_column.forEach(function(item){
        btns.push({id:item.id,text:'<input type="checkbox">'+item.name});
    });
    new bsEx.BtnGroup({
        renderto:"#btngroupid",
        btns:btns
    });
    $('#btnall').on('click',function(){
        if(!$(this).hasClass('active')){
            $('#btngroupid').find('.btn.btn-default').addClass('active');
        }else{
            $('#btngroupid').find('.btn.btn-default').removeClass('active');
        }
    })
    
    $('#btns').append('<button id="btn_out" class="btn btn-default">导出</button>');
    $('#btn_out').on('click',btn_out)
    
    $('#btnTables').html('');
    $('#btnTables').append('<p/><div id="btntablesid"  data-toggle="buttons" class="btn-group"></div>&nbsp;&nbsp;');
    var btntables = [];
    $.tablename.forEach(function(item){
        btntables.push({id:item,text:'<input type="radio" name="table"> '+item});
    })
    new bsEx.BtnGroup({
        renderto:"#btntablesid",
        btns:btntables
    });
    
    if($.CookieData.maintable){
        $('#'+$.CookieData.maintable).addClass('active');
    }

    if($.CookieData.outcolumn){
        $.CookieData.outcolumn.forEach(function(item){
            $('#'+item).addClass('active');
        })
    }
}
//导出Excel
function btn_out(){
    //得到选择了哪些列
    var btns = $('#btngroupid').find('.btn.active');
    var checkbtns = [];
    $.each(btns,function(i,b){
        if($(b).attr('id')!='btnall'){
            checkbtns.push($(b).attr('id'));
        }
    })
    //console.log(checkbtns)
    //得到选择的主表
    var btntable = $('#btntablesid').find('.btn.active');
    var table = btntable.attr('id');
    //console.log(table)
    //得到编辑配置 格式为[{table1:col1,ope:''=},table2:col2]
    var relation = [];
    var formdata = form1.getFormData();
    //console.log(formdata)
    var rows = [];
    for(var v in formdata ){
        if(v.indexOf('ope_')>=0){
            rows.push(v.split('_')[1]);
        }
    }
    rows.forEach(function(index){
        var datarow = {};
        var A = formdata['tablename_column_'+index+'_A'];
        var ope = formdata['ope_'+index];
        var B = formdata['tablename_column_'+index+'_B'];
        if(A && ope && B){
            datarow[A.split('_')[0]] = A.replace(A.split('_')[0]+'_','');
            datarow['ope'] = ope;
            datarow[B.split('_')[0]] = B.replace(B.split('_')[0]+'_','');
            datarow['A'] =A.split('_')[0];
            datarow['B'] =B.split('_')[0];
            if(A.split('_')[0]==table || B.split('_')[0]==table){
                datarow['mainrelation'] = 'true';
            }else{
                datarow['mainrelation'] = 'false';
            }
            relation.push(datarow);
        }
    })
    console.log(relation)
    GetOutData(table,checkbtns,relation);
}
//新增按钮
function InitButton2(){
    new bsEx.Button({
       id:'btn_new',
       renderto:"#btn_new",
       icon:"plus",
       text:false,
       btntype:"primary"//按钮类型
       ,isdisabled:true
    }); 
    $.rownub = 1;  
    $.FormData = {}; 
    //新增按钮事件
    bsEx.ui.btn_new.on("click",function(){
       $.FormData = form1.getFormData();
       if($.CookieData.rownub && $.rownub == 1){
            $.rownub = $.CookieData.rownub;
       }
       $.rownub++;
       form1.items.push({type: 'select', name: 'tablename_column_'+$.rownub+'_A', title: '表名_列名:', select: { data: $.tablename_column, tree: false } });
       form1.items.push({type: 'text', name: 'ope_'+$.rownub+'', title: '运算符:', value:"=" });
       form1.items.push({type: 'select', name: 'tablename_column_'+$.rownub+'_B', title: '表名_列名:', select: { data: $.tablename_column, tree: false } });
       form1.items.push({type: 'text', name: 'delbtn_'+$.rownub+'', title: '', select: { data: [], tree: false } });
       form1.readonly.push('ope_'+$.rownub+'');
       form1.init();
    })
}
//初始化 excel 导入
function InitExcelHelp(){
   $._ExcelHelp = new ExcelHelp();
   $._ExcelHelp.on('typeErr',function(){
       //错误 提示错误
       bsEx.Alert("提示","文件类型不正确。<br/>请重新选择文件",3);
       $('#fileurl').val();
   }).on('select',function(file){//没错显示文件名
       $('#fileurl').val(file.name);
       //拿到cookie值
       //$.CookieData = {};
       $.CookieData = getCookie()||{};
       console.log($.CookieData);
       //开始读取后初始化
       $._ExcelHelp.read(read);
   });
   //初始化加载按钮
   $('#btnfile').on('click',function(){
       $._ExcelHelp.select();
   })
}
//读取Excel
function read(exceldata,sheets){
   var count =  exceldata.length;
   //表名和列
   $.tablename_column = [];
   //表名
   $.tablename =[];
   for(var i =0; i<count;i++){
       var data = exceldata[i];
       var tname = sheets[i];
       for(var v in data[0]){
           var tc = {};
           tc['name'] = tname+'_'+v; 
           tc['id'] = tname+'_'+v; 
           $.tablename_column.push(tc);
       }
       $.tablename.push(tname);
    }
   //开启
   bsEx.ui.btn_new.setdisabled(false);
   //开始绘制表单
   InitForm1();
   //选择列
   InitButs();
}
//核心方法 根据配置处理导出Excel
function GetOutData(maintable,outcolumn,relation){
    $._ExcelHelp.read(function(excelData,sheets){
        var mainindex = sheets.indexOf(maintable);
        var mainData = excelData[mainindex];
        //返回的新表
        var newData = [];
        var outtable = [];
        outcolumn.forEach(function(item){
            var _outtable = item.split('_')[0];
            if(outtable.indexOf(_outtable)<0 && _outtable!=maintable ){
                outtable.push(_outtable);
            }
        })
        //主表关系
        var mainrelation = relation.filter(function(m){return m.A==maintable || m.B==maintable});
        mainData.forEach(function(mainrow,mainrowindex){
            //所有导出的行
            var newRow = {};
            outcolumn.forEach(function(item){
                newRow[item]="";
            });
            //找到所有 主表要导出的
            for(var mc in mainrow){
                if(outcolumn.indexOf(maintable+'_'+mc)>=0){
                    newRow[maintable+'_'+mc] = mainrow[mc];
                }
            }
            //{sheet1:name,sheet2:name,ope:=}
            outtable.forEach(function(_outtable){
                //当前表数据
                var outdata = excelData[sheets.indexOf(_outtable)];
                //当前表和主表对比
                var otherrelation = relation.filter(function(m){return (m.A==_outtable && m.B==maintable) || (m.B==_outtable && m.A==maintable)});
                //var othertable 
                //拼接 当前表和主笔的所有条件
                var eves = [];
                otherrelation.forEach(function(ra){
                    eves.push("_item['"+ra[_outtable]+"']==mainrow['"+ra[maintable]+"']");
                })
                //如果有条件
                if(eves.length>0){
                    //执行查找
                    eval('var rows =outdata.find(function(_item){ return '+eves.join(' && ')+'})');
                    if(rows){
                        //newRow[_outtable+'_'+mc] = rows[mc];
                        //如果导出的列包含当前表 就赋值
                        outcolumn.forEach(function(_o){
                            if(_o.indexOf(_outtable+'_')>=0){
                                newRow[_o] = rows[_o.replace(_o.split('_')[0]+'_','')];
                            }
                        })
                        //找到当前表和其他表关系 A=B
                        var getsonrow = function(santable,parentrow){
                            var thisrelation_A = relation.filter(function(m){return (m.A==santable && m.B!=maintable && !m['done_'+mainrowindex])});
                            thisrelation_A.forEach(function(item){
                                item['done_'+mainrowindex] = true;
                                var this_outdata = excelData[sheets.indexOf(item.B)];
                                var this_eves = "_item['"+item[item.B]+"']==parentrow['"+item[item.A]+"']";
                                eval('var thisrows =this_outdata.find(function(_item){ return '+this_eves+'})');
                                //console.log('var thisrows =this_outdata.find(function(_item){ return '+this_eves+'})')
                                if(thisrows){
                                    outcolumn.forEach(function(_o){
                                        if(_o.indexOf(item.B+'_')>=0){
                                            newRow[_o] = thisrows[_o.replace(_o.split('_')[0]+'_','')];
                                        }
                                    })
                                    getsonrow(item.B,thisrows);
                                }
                            })
                            //其他表和当前表关系 B=A
                            var thisrelation_B = relation.filter(function(m){return (m.B==santable && m.A!=maintable&& !m['done_'+mainrowindex])});
                            thisrelation_B.forEach(function(item){
                                item['done_'+mainrowindex] = true;
                                var this_outdata = excelData[sheets.indexOf(item.A)];
                                var this_eves = "_item['"+item[item.A]+"']==parentrow['"+item[item.B]+"']";
                                eval('var thisrows =outdata.find(function(_item){ return '+this_eves+'})');
                                //console.log('var thisrows =outdata.find(function(_item){ return '+this_eves+'})')
                                if(thisrows){
                                    outcolumn.forEach(function(_o){
                                        if(_o.indexOf(item.A+'_')>=0){
                                            newRow[_o] = thisrows[_o.replace(_o.split('_')[0]+'_','')];
                                        }
                                    })
                                    getsonrow(item.A,thisrows);
                                }
                            })
                        }
                        getsonrow(_outtable,rows);
                    }
                }
                
            })
            newData.push(newRow);
        });
        //console.log(newData);
        $._ExcelHelp.out("结果",newData,[]);
        setCookie();
    })
}
//存储到cookie
function setCookie(){
    var name = 'ExcelHelp_tool_'+$._ExcelHelp.file.name;
    var value = {};
    value.formitem = form1.items;
    value.formdata = form1.getFormData();
    value.rownub = $.rownub;
    var btns = $('#btngroupid').find('.btn.active');
    var checkbtns = [];
    $.each(btns,function(i,b){
        if($(b).attr('id')!='btnall'){
            checkbtns.push($(b).attr('id'));
        }
    })
    //console.log(checkbtns)
    //得到选择的主表
    var btntable = $('#btntablesid').find('.btn.active');
    var table = btntable.attr('id');
    value.outcolumn = checkbtns;
    value.maintable = table;
    //console.log('存'+name)
    //console.log(value)
    //$.cookie(name,  JSON.stringify(value), { expires: 365 });
    setStorage(name,value);
}
//得到 cookie
function getCookie(){
    var name = 'ExcelHelp_tool_'+$._ExcelHelp.file.name;
    //console.log('取'+name)
    //var json = $.cookie(name);
    var json = getStorage(name);
    if(json){
        return  JSON.parse(json);
    }
}
//自定义localstorage的过期逻辑
function setStorage(key,val){
    var curTime=new Date().getTime();
    localStorage.setItem(key,JSON.stringify(val))
}
function getStorage(key){
    var data=localStorage.getItem(key);
    return data;
}